from django.shortcuts import render
import json,re,random,io,sys,requests,time

from django.views import View
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt

from py2neo import Graph,Node,Relationship
graph = Graph(host='localhost',auth=('neo4j','123'))


@csrf_exempt
def gy_findTypes(request):
    global graph
    sql = "MATCH (n:YanJiuFangXiang) RETURN n as type"
    try:
        nodes_source = graph.run(sql).data()
        return JsonResponse({"status": "ok", "success": True, "data": nodes_source})
    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "ok", "success": False, "data": ex})

@csrf_exempt
def gy_findByType(request):
    global graph
    type = eval(request.body.decode()).get('type')
    sql = "MATCH (n:YanJiuFangXiang) -[]->(lunwen)  where n.`研究方向` = '"+ type +"' RETURN n as type, lunwen"
    try:
        nodes_source = graph.run(sql).data()
        return JsonResponse({"status": "ok", "success": True, "data": nodes_source})
    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "ok", "success": False, "data": ex})

@csrf_exempt
def gy_findByParams(request):
    global graph
    # sql = eval(request.body.decode()).get('sql')
    typePre = eval(request.body.decode()).get('typePre')
    typeNext = eval(request.body.decode()).get('typeNext')
    inputNext = eval(request.body.decode()).get('inputNext')

    if typePre == '' or typeNext == '':
        return JsonResponse({"status":"error","success":False})
    else:
        try:
            sql = "MATCH (type:YanJiuFangXiang) -[]->( lunwen:LunWen) where type.`研究方向` = '"+typePre+"' and lunwen.`"+typeNext+"` =~'.*" + inputNext + ".*' Return type, lunwen"
            nodes_source = graph.run(sql).data()
            return JsonResponse({"status": "ok","success": True,"data":nodes_source})
        except Exception as ex:
            print(ex)
            return JsonResponse({"status": "ok","success": False,"data":ex})


@csrf_exempt
def findBySql(request):
    global graph
    sql = eval(request.body.decode()).get('sql')
    if sql == '':
        return JsonResponse({"status":"error","success":False})
    else:
        try:
            nodes_source = graph.run(sql).data()
            return JsonResponse({"status": "ok","success": True,"data":nodes_source})
        except Exception as ex:
            print(ex)
            return JsonResponse({"status": "ok","success": False,"data":ex})